﻿using AutoMapper;
using MediatR;
using RBAC_Uthorization.API.Application.Command.RoleCommand;
using RBAC_Uthorization.API.DTO;
using RBAC_Uthorization.API.Extensions;
using RBAC_Uthorization.Domain;
using RBAC_Uthorization.Infrstructre.Impl;
using RBAC_Uthorization.Infrstructre.Interface;
using StackExchange.Redis;

namespace RBAC_Uthorization.API.Application.CommandHandlers.RoleHandler
{
    public class RoleDeleteCommandHandlers : IRequestHandler<RoleDeleteCommand, ApiResult<int>>
    {
        private readonly IRoleRepository _roleRepository;
        private readonly ILogger<RoleDeleteCommandHandlers> _logger;
        private readonly IRoleMenuRepository _roleMenuRepository;
        private readonly IRoleMenuFuncRepository _roleMenuFuncRepository;
        private readonly IConfiguration _configuration;
        private readonly IUserRoleRepository _userRoleRepository;
        private readonly RedisConnectionService _redisConnectionService;



        public RoleDeleteCommandHandlers(ILogger<RoleDeleteCommandHandlers> logger, IRoleRepository roleRepository, IRoleMenuRepository roleMenuRepository, IRoleMenuFuncRepository roleMenuFuncRepository, IConfiguration configuration, IUserRoleRepository userRoleRepository, RedisConnectionService redisConnectionService)
        {
            _logger = logger;
            _roleRepository = roleRepository;
            _roleMenuRepository = roleMenuRepository;
            _roleMenuFuncRepository = roleMenuFuncRepository;
            _configuration = configuration;
            _userRoleRepository = userRoleRepository;
            _redisConnectionService = redisConnectionService;
        }

        public async Task<ApiResult<int>> Handle(RoleDeleteCommand request, CancellationToken cancellationToken)
        {
            _roleMenuFuncRepository.BeginTransactionAsync();
            try
            {

                if (_configuration["Redis:Redisif"] == "1")
                {
                    
                    foreach (var item in request.id)
                    {
                        var userid = await _userRoleRepository.GetAllAsunc(x => x.role_id == item && x.del_flag == 0);
                        foreach (var items in userid)
                        {
                            if (items != null)
                            {
                                await _redisConnectionService.DeleteAsync($"user:{items.user_id}:{request.sys_id}:roleIds");
                                await _redisConnectionService.DeleteAsync($"user:{items.user_id}:{request.sys_id}:menuIds");
                            }
                        }
                        


                    }
                }

                foreach (var item in request.id)
                {
                    var datalist = await _roleRepository.GetAllAsunc(x => x.id == item && x.del_flag == 0);
                    var data = datalist.FirstOrDefault();
                    if (data == null)
                    {
                        return new ApiResult<int>
                        {
                            Code = ResultCode.Fail,
                            Message = "角色信息不存在"
                        };
                    }
                    data.del_flag = 1;
                    data.update_by = request.Createby;
                    data.update_date = DateTime.UtcNow;
                    var result = await _roleRepository.UpdateAsync(data);
                    //查询角色菜单信息
                    var rolemenu = await _roleMenuRepository.GetAllAsunc(x => x.role_id == item && x.del_flag == 0);
                    if (rolemenu != null)
                    {
                        foreach (var rolemenuitem in rolemenu)
                        {
                            await _roleMenuRepository.DeleteAsync(rolemenuitem.id);
                        }
                    }

                    //查询角色菜单功能信息
                    var rolemenufunc = await _roleMenuFuncRepository.GetAllAsunc(x => x.role_id == item && x.del_flag == 0);
                    if (rolemenufunc != null)
                    {
                        foreach (var item2 in rolemenufunc)
                        {
                            item2.update_date = DateTime.UtcNow;
                            item2.update_by = request.Createby;
                            item2.del_flag = 1;
                            await _roleMenuFuncRepository.DeleteAsync(item2.id);
                        }
                    }


                }
                _roleMenuFuncRepository.CommitTransactionAsync();
                _logger.LogInformation($"删除角色信息成功:{request.id}");
                return new ApiResult<int>();
            }
            catch (Exception e)
            {
                _roleMenuFuncRepository.RollbackTransactionAsync();
                _logger.LogError($"删除角色信息失败:{e.Message}->{e.StackTrace}->{e.InnerException}");
                return new ApiResult<int>
                {
                    Code = ResultCode.Fail,
                    Message = "删除角色信息失败"
                };
            }
        }
    }
}
